package com.gwt.gateway.filter;

import cn.hutool.extra.spring.SpringUtil;
import com.gwt.auth.feign.AuthFeign;
import com.gwt.auth.vo.AuthTokenVO;
import com.gwt.cloud.result.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthFilter.class);

    @Value("#{'${auth.skip.urls}'.split(',')}")
    private String[] skipUrls;

    @Override
    public int getOrder() {
        return -100;
    }

    @Resource
    private MessageResponse messageResponse;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServerHttpResponse response = exchange.getResponse();
        //身份认证
        AuthFeign authFeign = SpringUtil.getBean(AuthFeign.class);
        CompletableFuture<ApiResult<AuthTokenVO>> completableFuture = CompletableFuture.supplyAsync(() -> {
                    // 复制主线程的 线程共享数据
                    RequestContextHolder.setRequestAttributes(attributes);
                    ApiResult<AuthTokenVO> result = authFeign.tokenValidate();
                    return result;
                }
        );
        ApiResult<AuthTokenVO> result = Optional.ofNullable(completableFuture).map(item -> {
            try {
                return item.get();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        }).get();
        if (result == null || !result.getSuccess() || result.getData() == null){
            return messageResponse.result(exchange, result.getStatus(), result.getMessage());
        }
        //将现在的request，添加当前用户ID
        ServerWebExchange mutableExchange = exchange.mutate().build();
        return chain.filter(mutableExchange);
    }
}